package org.zn.mvcbase.controller;


import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.zn.mvcbase.config.property.BootMvcProperty;


/**
 * @Description: 
 * @Copyright: Copyright (c) 2018

 * @author: 周楠
 * @date 2018年6月27日 下午1:08:40
 */
@Controller
@ConfigurationProperties(prefix=BootMvcProperty.BOOT_PREFIX)
@ConditionalOnProperty(prefix="bootmvc.viewgate",name="enable",havingValue="true",matchIfMissing=true)
public class ViewGateWay extends ResponseMessageController{

	private Logger log=LoggerFactory.getLogger(ViewGateWay.class);
	
	
	public ViewGateWay() {
		
		log.info("ViewGateWay init");
		
	}

	
	@Value("${bootmvc.viewgate.mode:jar}")
	private String mode;
	
	@Value("${bootmvc.viewgate.suffix:view}")
	private String suffix;
	
	private String sessionTag = ";jsessionid=";
	
	
	@GetMapping(value = "${bootmvc.viewgate.suffix:view}/**")
	public String common(HttpServletRequest request, HttpServletResponse response , Model model) {
		
		
		String requestURI = request.getRequestURI();
		
		Map<String, String[]> parameterMap = request.getParameterMap();
		
		Set<Entry<String, String[]>> pset = parameterMap.entrySet();

		if(requestURI.toLowerCase().indexOf(sessionTag) > 0) {
			String[] uri_session = requestURI.split(sessionTag);
			requestURI = uri_session[0];
			/*Cookie[] cookies = request.getCookies();
			boolean hasSession = false;
			if(cookies != null  && cookies.length == 0) {
				for (Cookie cookie : cookies) {
					if(cookie.getName().equals("JSESSIONID")) {
						cookie.setValue(uri_session[1]);
						hasSession = true;
						break;
					}
				}
			}
			
			if(!hasSession) {
				Cookie cookie = new Cookie("JSESSIONID", uri_session[1]);
				response.addCookie(cookie);	
			}*/
		}
		
		for (Entry<String, String[]> entry : pset) {
			model.addAttribute(entry.getKey(), entry.getValue());

		}
		
		String[] paths=requestURI.split(suffix);
		
		String  forword=paths[1];
		
		
		if(mode.equals("jar")) {
			
			forword=forword.replaceFirst("/", "");
			
		}
		
		log.info("forword : {}",forword);
		
		return forword;
	}

	


}
